package com.xx.sg.util;

import com.xx.sg.exception.ServiceException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class FileUploadUtils {

    /**
     * 将字节数组保存为图片文件
     *
     * @param imageBytes 图片的字节数组
     * @param path       图片保存目录，比如 "E:/upload/"
     * @return 返回保存的图片完整路径
     * @throws IOException 可能抛出文件写入异常
     */
    public static String saveImage(byte[] imageBytes, String path) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String dayStr = LocalDate.now().format(formatter);
        String dirPath = path + "/" + dayStr;
        File fileDir = new File(dirPath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        // 使用时间戳生成新文件名
        String newFileName = System.currentTimeMillis() + ".jpg";
        String filePath = dirPath + "/" + newFileName;
        // 写文件
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(imageBytes);
            fos.flush();
        } catch (IOException e) {
            throw new ServiceException("图片保存失败");
        }
        return "/" + dayStr + "/" + newFileName;
    }

    public static String uploadFile(String filePath, String dirName, MultipartFile file) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String dayStr = LocalDate.now().format(formatter);
        String dirPath = filePath + "/" + dirName + "/" + dayStr;
        File fileDir = new File(dirPath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        // 获取文件扩展名
        String originalFilename = file.getOriginalFilename();
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        // 使用时间戳生成新文件名
        String newFileName = System.currentTimeMillis() + extension;
        String newFilePath = dirPath + "/" + newFileName;
        // 保存文件
        File dest = new File(newFilePath);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("文件上传失败");
        }
        return "/" + dirName + "/" + dayStr + "/" + newFileName;
    }
}
